import { createHelia } from 'helia'
import { unixfs } from '@helia/unixfs'


// 创建Helia实例
const helia = await createHelia()

// unixfs传输实例
const heliaUnixFS = unixfs(helia)

// 创建一个目录
const dirPath = 'my_files'
const newDirCid = await heliaUnixFS.addDirectory()
console.log("newDirCid =", newDirCid.toString())
const mkdirCid = await heliaUnixFS.mkdir(newDirCid, dirPath)
console.log("mkdirCid =", mkdirCid.toString())
const dirStat = await heliaUnixFS.stat(mkdirCid, {
    path: dirPath
})
const dirCid = dirStat.cid
console.log("dirCid =", dirCid.toString())

// 查询目录
for await (const entry of heliaUnixFS.ls(mkdirCid)) {
    console.log('entry：', entry.name, entry.type, entry.cid.toString())
}

// 创建一个文件
const newFileCid = await heliaUnixFS.addFile({
    content: new TextEncoder().encode('hello world')
})
console.log("newFileCid =", newFileCid.toString())
const fileDirCid = await heliaUnixFS.cp(newFileCid, dirCid, 'hello.txt')
console.log("fileDirCid =", fileDirCid.toString())

// 查询目录
for await (const entry of heliaUnixFS.ls(fileDirCid)) {
    console.log('entry：', entry.name, entry.type, entry.cid.toString())
}

// 获取文件内容
let fileContent = ''
const textDecoder = new TextDecoder()
for await (const buf of heliaUnixFS.cat(newFileCid)) {
    fileContent += textDecoder.decode(buf, {
        stream: true
    })
}
console.log('fileContent = ', fileContent)

